<?php
// +----------------------------------------------------------------------
// | title: 标题注释
// +----------------------------------------------------------------------
// | Author: TZ.Leong
// +----------------------------------------------------------------------
// | Date: 2019/7/3 20:32
// +----------------------------------------------------------------------

namespace app\single\model;


use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class VarModel extends Model
{
    /**
     * @var null
     */
    protected $table;

    public function initialize()
    {
        $this->table = "sys_var";
    }

    /**
     * 根据name或者配置表的值
     * @param $name
     * @return mixed
     */
    public function getValue($name)
    {
        return $this->where(array("name" => $name))->value("value");
    }

    /**
     * 更新数据
     * @param mixed|string $name
     * @param mixed $value
     * @return bool
     */
    public function saveData($name, $value)
    {
        try {
            return $this->where(array("name" => $name))->update(array("value" => $value));
        } catch (PDOException|Exception $e) {
            return false;
        }
    }

    /**
     * 插入数据
     * @param mixed|string $name
     * @param mixed|string $value
     * @return int|string
     */
    public function addData($name, string $value)
    {
        return $this->insert(array("name" => $name, "value" => $value));
    }

    /**
     * 更新数据
     * @param $name
     * @param $value
     * @return bool|null
     */
    public function replaceData($name, $value): ?bool
    {
        $info = $this->where("name", $name)->find();
        if($info){
            $res = $this->saveData($name,$value);
        }else{
            $res = $this->addData($name,$value);
        }
        return $res;
    }
}